﻿using System.Web.Mvc;
using Kooboo.Commerce;
using Kooboo.Commerce.Contexts.Accounts;
using Kooboo.Connect;
using Kooboo.IoC;
using System.Linq;
using Kooboo.Globalization;


namespace Kooboo.Web.Areas.Commerce.Controllers
{

    [Authorize(Roles = "Administrator")]
    public class AccountController : ManagementController
    {
        public ActionResult Index()
        {

            ViewData["Administrators"] = this.Actor.QueryAdministrators().AsEnumerable();

            return View(ObjectContainer.CreateInstance<IAdministrator>());
        }

        [HttpPost]
        public ActionResult AddAdministrator(IAdministrator administrator)
        {

            try
            {

                if (this.Actor.QueryAdministrators().Any(i => i.UserName == administrator.UserName))
                {
                    ModelState.AddModelError("UserName", "already exists.".Localize());
                }

                if (UserServices.FindUser(administrator.UserName) == null)
                {
                    ModelState.AddModelError("UserName", "this user doesn't exist.".Localize());
                }

                if (ModelState.IsValid)
                {
                    this.Actor.Post(administrator);
                }
            }
            catch
            {

            }

            return this.RedirectToAction("Index");
        }

        [HttpPost]
        public ActionResult DeleteAdministrator(string userName)
        {

            try
            {
                var administrator = this.Actor.QueryAdministrators().FirstOrDefault(i => i.UserName == userName);
                if (administrator != null)
                {
                    this.Actor.Delete(administrator);
                }
            }
            catch
            {

            }

            ViewData["Administrators"] = this.Actor.QueryAdministrators().AsEnumerable();

            return this.RedirectToAction("Index");
        }


        #region Change Password
        public ActionResult ChangePassword()
        {
            return View();
        }


        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {
                if (model.TryChange(User.Identity.Name))
                {
                    return RedirectToAction("ChangePasswordSuccess");
                }
                else
                {
                    ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.".Localize());
                }
            }

            return View(model);
        }
        #endregion
    }
}
